home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / programr / mathstud.zip / DIAG.M < prev    next >
Text File  |  1993-05-28  |  1KB  |  51 lines

  1. function y = diag(X,k)
  2. %y=diag(X,k)
  3. %Extract the diagonal elements of a matrix
  4. %Convert a vector to a diagonal matrix
  5.  
  6. %       S.Halevy 7/31/92
  7. %       Copyright (c) 1992 by the MathWizards
  8.  
  9. if nargin < 1
  10.    y=[];
  11.    return;
  12. elseif nargin < 2
  13.     k=0;
  14. elseif nargin>2
  15.     error('diag - too many input arguments')
  16. end
  17.  
  18. k0=k+1;        % k=0 for the main diagonal
  19.  
  20. if isvector(X)   % VECTOR
  21.    X=X(:);
  22.    nx = length(X);
  23.    ny = nx + abs(k);
  24.    y=zeros(ny);
  25.  
  26.    k0 = expr_sel(k>=0,ny*k,abs(k))+1;
  27.  
  28.    for ik=1:nx
  29.        y(k0)=X(ik);
  30.        k0 += ny+1;
  31.    end
  32. else    % MATRIX
  33.    [m,n] = size(X);
  34.    mstep = m+1;
  35.    k0=1;
  36.    if k>0
  37.       k0+=m*k;  % first element
  38.       n -= k;       % row shift
  39.    else             % negative k
  40.       k0 += (-k); % first element
  41.       m -=   (-k); % col shift
  42.    end
  43.    k0 = max(1, k0);       % first element
  44.    ny = max(0, min(m,n)); % size of output
  45.    y=zeros(ny,1); % empty if ny<=0
  46.    if ny>0
  47.      iy=1:ny;
  48.      y(iy)=X(k0+mstep*(iy-1))';
  49.   end
  50. end
  51.